package logic

import (
	"context"
	"errors"
	"fmt"
	"pro-train-hub/models/mysql"
	"pro-train-hub/pkg"
	"time"

	"pro-train-hub/trainrpc/internal/svc"
	"pro-train-hub/trainrpc/trainrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type PasswordLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPasswordLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PasswordLoginLogic {
	return &PasswordLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *PasswordLoginLogic) PasswordLogin(in *trainrpc.PasswordLoginRequest) (*trainrpc.PasswordLoginResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&user)

	timeStamp := time.Now().Unix()
	if user.ID == 0 {
		user = mysql.User{
			Username: fmt.Sprintf("用户_%d", timeStamp),
			Avatar:   "http://t2u3h1i1n.hn-bkt.clouddn.com/1cdd12d9e59f408c82ac6c8c8a75055f.jpg",
			Mobile:   in.Mobile,
			Password: pkg.Md5string(in.Password),
		}
		mysql.DB.Debug().Create(&user)
	}
	if user.Password != pkg.Md5string(in.Password) {
		return nil, errors.New("账号或密码有误，请重新输入")
	}
	return &trainrpc.PasswordLoginResponse{
		UserId: int64(user.ID),
	}, nil
}
